/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.databean;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class User {
	private String  userName = null;
	private String  hashedPassword = "*";
	private int     salt           = 0;
	private int     numberofSchedule = 0;
	private int		currentSchedule = 0;
	
	public User(String userName) {
		this.userName = userName;
	}

	public boolean checkPassword(String password) {
		return hashedPassword.equals(hash(password));
	}

	public String  getHashedPassword()	{ return hashedPassword; }
	public String  getUserName()		{ return userName;       }
	public int     getSalt()			{ return salt;           }
	public int     getNumSchedule()		{ return numberofSchedule; }
	public int     getCurrentSchedule()	{ return currentSchedule; }
	
	public void setHashedPassword(String var)	{ hashedPassword = var; }
	public void setPassword(String var)			{ salt = newSalt(); hashedPassword = hash(var); }
	public void setSalt(int var)				{ salt = var; }
	public void setNumSchedule(int var)			{ numberofSchedule = var; }
	public void setCurrentSchedule(int var)		{ currentSchedule = var; }
	
	
	public String toString() {
		return "User("+getUserName()+")";
	}

	private String hash(String clearPassword) {
		MessageDigest md = null;
		try {
		  md = MessageDigest.getInstance("SHA1");
		} catch (NoSuchAlgorithmException e) {
		  throw new AssertionError("Can't find the SHA1 algorithm in the java.security package");
		}

		String saltString = String.valueOf(salt);
		
		md.update(saltString.getBytes());
		md.update(clearPassword.getBytes());
		byte[] digestBytes = md.digest();

		// Format the digest as a String
		StringBuffer digestSB = new StringBuffer();
		for (int i=0; i<digestBytes.length; i++) {
		  int lowNibble = digestBytes[i] & 0x0f;
		  int highNibble = (digestBytes[i]>>4) & 0x0f;
		  digestSB.append(Integer.toHexString(highNibble));
		  digestSB.append(Integer.toHexString(lowNibble));
		}
		String digestStr = digestSB.toString();

		return digestStr;
	}

	private int newSalt() {
		Random random = new Random();
		return random.nextInt(Integer.MAX_VALUE-1)+1;  // salt cannot be zero, except for uninitialized password
	}
}
